package com.chuantou.yuba.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.chuantou.yuba.api.to.UserTO;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class AccountManager {
	private static final String FILE_NAME = ".amg.xml";
	private static final String KEY_USER = "jdwadjwioaju";
	private static AccountManager sManager;
	private UserTO mUser;

	private AccountManager(Context context) {
		try {
			SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
			String sCipherText = preferences.getString(KEY_USER, null);
			if (TextUtils.isEmpty(sCipherText))
				return;
			Blowfish blowfish = new Blowfish(KEY_USER);
			String jsonString = blowfish.decryptString(sCipherText);
			Gson gson = new Gson();
			mUser = gson.fromJson(jsonString, UserTO.class);
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
		}
	}

	public synchronized static AccountManager getInstance(Context context) {
		return sManager == null ? sManager = new AccountManager(context) : sManager;
	}

	public boolean isLogined() {
		return mUser != null && mUser.getUid() > 0;
	}

	public void setUserTO(UserTO user) {
		this.mUser = user;
	}

	public UserTO getUserTO() {
		return mUser;
	}

	public static void saveUser(Context context, UserTO userTO) {
		if (userTO == null)
			return;
		SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		Blowfish blowfish = new Blowfish(KEY_USER);
		String encryptString = blowfish.encryptString(userTO.toJsonString());
		preferences.edit().putString(KEY_USER, encryptString).commit();
		getInstance(context).setUserTO(userTO);
	}

	public static void logout(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		preferences.edit().clear().commit();
		getInstance(context).setUserTO(null);
	}

}
